<%#
 Copyright 2013-2020 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.config;

<%_ if (authenticationType === 'session' || authenticationType === 'jwt' || authenticationType === 'oauth2') { _%>
import <%= packageName %>.security.*;
    <%_ if (authenticationType === 'jwt') { _%>
import <%= packageName %>.security.jwt.*;
    <%_ } _%>
    <%_ if (authenticationType === 'session') { _%>

        <%_ if (!skipUserManagement) { _%>
import io.github.jhipster.config.JHipsterProperties;
        <%_ } _%>
import io.github.jhipster.security.*;
    <%_ } _%>

    <%_ if (authenticationType === 'oauth2') { _%>
import io.github.jhipster.config.JHipsterProperties;
    <%_ } _%>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
    <%_ if (authenticationType === 'oauth2') { _%>
import org.springframework.core.convert.converter.Converter;
    <%_ } _%>
    <%_ if (authenticationType !== 'uaa' && !(applicationType === 'microservice' && authenticationType === 'oauth2')) { _%>
import org.springframework.http.HttpMethod;
    <%_ } _%>
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    <%_ if (authenticationType !== 'uaa' && !(applicationType === 'microservice' && authenticationType === 'oauth2')) { _%>
import org.springframework.security.config.annotation.web.builders.WebSecurity;
    <%_ } else { _%>
        <%_ if (devDatabaseType === 'h2Disk' || devDatabaseType === 'h2Memory') { _%>
import org.springframework.security.config.annotation.web.builders.WebSecurity;
        <%_ } _%>
    <%_ } _%>
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    <%_ if (authenticationType === 'jwt' || (authenticationType === 'oauth2' && applicationType === 'microservice')) { _%>
import org.springframework.security.config.http.SessionCreationPolicy;
    <%_ } _%>
    <%_ if (authenticationType !== 'oauth2' && !skipUserManagement) { _%>
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
    <%_ } _%>
    <%_ if (authenticationType === 'oauth2') { _%>
import <%= packageName %>.security.oauth2.AudienceValidator;
import <%= packageName %>.security.SecurityUtils;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jwt.*;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
        <%_ if (applicationType === 'gateway' && serviceDiscoveryType) { _%>
import <%= packageName %>.security.oauth2.AuthorizationHeaderFilter;
import <%= packageName %>.security.oauth2.AuthorizationHeaderUtil;
        <%_ } _%>
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
        <%_ if (applicationType !== 'microservice') { _%>
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
        <%_ } _%>
import java.util.*;
    <%_ } _%>
    <%_ if (authenticationType === 'session') { _%>
        <%_ if (!skipUserManagement) { _%>
import org.springframework.security.web.authentication.RememberMeServices;
        <%_ } _%>
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfFilter;
    <%_ } _%>
    <%_ if (authenticationType === 'oauth2' && applicationType !== 'microservice') { _%>
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfFilter;
    <%_ } _%>
    <%_ if (authenticationType === 'oauth2') { _%>
import <%= packageName %>.security.oauth2.JwtGrantedAuthorityConverter;
    <%_ } _%>
    <%_ if (authenticationType === 'jwt' && applicationType !== 'microservice') { _%>
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    <%_ } _%>
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
    <%_ if (applicationType !== 'microservice') { _%>
import org.springframework.web.filter.CorsFilter;
    <%_ } _%>
import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    <%_ if (authenticationType === 'session' && !skipUserManagement) { _%>

    private final JHipsterProperties jHipsterProperties;

    private final RememberMeServices rememberMeServices;
    <%_ } _%>
    <%_ if (authenticationType === 'jwt') { _%>

    private final TokenProvider tokenProvider;
    <%_ } _%>
    <%_ if (applicationType !== 'microservice') { _%>

    private final CorsFilter corsFilter;
    <%_ } _%>
    <%_ if (authenticationType === 'oauth2') { _%>

    @Value("${spring.security.oauth2.client.provider.oidc.issuer-uri}")
    private String issuerUri;

    private final JHipsterProperties jHipsterProperties;
    <%_ } _%>
    private final SecurityProblemSupport problemSupport;

    public SecurityConfiguration(<% if (authenticationType === 'session' && !skipUserManagement) { %>JHipsterProperties jHipsterProperties, RememberMeServices rememberMeServices, <% } if (authenticationType === 'jwt') { %>TokenProvider tokenProvider, <% } %><% if (applicationType !== 'microservice') { %>CorsFilter corsFilter, <% } %><% if (authenticationType === 'oauth2') { %>JHipsterProperties jHipsterProperties, <% } %>SecurityProblemSupport problemSupport) {
    <%_ if (authenticationType === 'session' && !skipUserManagement) { _%>
        this.jHipsterProperties = jHipsterProperties;
        this.rememberMeServices = rememberMeServices;
    <%_ } _%>
    <%_ if (authenticationType === 'jwt') { _%>
        this.tokenProvider = tokenProvider;
    <%_ } _%>
    <%_ if (applicationType !== 'microservice') { _%>
        this.corsFilter = corsFilter;
    <%_ } _%>
        this.problemSupport = problemSupport;
    <%_ if (authenticationType === 'oauth2') { _%>
        this.jHipsterProperties = jHipsterProperties;
    <%_ } _%>
    }
    <%_ if (authenticationType === 'session') { _%>

    @Bean
    public AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler() {
        return new AjaxAuthenticationSuccessHandler();
    }

    @Bean
    public AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler() {
        return new AjaxAuthenticationFailureHandler();
    }

    @Bean
    public AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler() {
        return new AjaxLogoutSuccessHandler();
    }
    <%_ } _%>
    <%_ if (authenticationType !== 'oauth2' && !skipUserManagement) { _%>

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    <%_ } _%>
    <%_ if (authenticationType !== 'uaa' && applicationType !== 'microservice') { _%>

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**")
        <%_ if (!skipClient) { _%>
            .antMatchers("/app/**/*.{js,html}")
            .antMatchers("/i18n/**")
            .antMatchers("/content/**")
        <%_ } _%>
        <%_ if (devDatabaseType === 'h2Disk' || devDatabaseType === 'h2Memory') { _%>
            .antMatchers("/h2-console/**")
        <%_ } _%>
            .antMatchers("/swagger-ui/index.html")
            .antMatchers("/test/**");
    }
    <%_ } else { _%>
        <%_ if (devDatabaseType === 'h2Disk' || devDatabaseType === 'h2Memory') { _%>
    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers("/h2-console/**");
    }
        <%_ } _%>
    <%_ } _%>

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .csrf()
    <%_ if (['session','oauth2'].includes(authenticationType) && applicationType !== 'microservice') { _%>
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
    <%_ } else { _%>
            .disable()
    <%_ } _%>
    <%_ if (applicationType !== 'microservice') { _%>
        <%_ if (authenticationType === 'jwt') { _%>
            .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
        <%_ } else if (authenticationType === 'session' || authenticationType === 'oauth2') { _%>
            .addFilterBefore(corsFilter, CsrfFilter.class)
        <%_ } _%>
    <%_ } _%>
            .exceptionHandling()
                .authenticationEntryPoint(problemSupport)
                .accessDeniedHandler(problemSupport)
    <%_ if (authenticationType === 'session') { _%>
        <%_ if (!skipUserManagement) { _%>
        .and()
            .rememberMe()
            .rememberMeServices(rememberMeServices)
            .rememberMeParameter("remember-me")
            .key(jHipsterProperties.getSecurity().getRememberMe().getKey())
        <%_ } _%>
        .and()
            .formLogin()
            .loginProcessingUrl("/api/authentication")
            .successHandler(ajaxAuthenticationSuccessHandler())
            .failureHandler(ajaxAuthenticationFailureHandler())
            .permitAll()
        .and()
            .logout()
            .logoutUrl("/api/logout")
            .logoutSuccessHandler(ajaxLogoutSuccessHandler())
            .permitAll()
    <%_ } _%>
        .and()
            .headers()
            <%_ if (clientTheme !== 'none') { _%>
            .contentSecurityPolicy("default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' https://fonts.googleapis.com 'unsafe-inline'; img-src 'self' data:; font-src 'self' https://fonts.gstatic.com data:")
            <%_ } else { _%>
            .contentSecurityPolicy("default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:")
            <%_ } _%>
        .and()
            .referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
        .and()
            .featurePolicy("geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; fullscreen 'self'; payment 'none'")
        .and()
            .frameOptions()
            .deny()
        .and()
    <%_ if (authenticationType === 'jwt' || (authenticationType === 'oauth2' && applicationType === 'microservice')) { _%>
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
    <%_ } _%>
            .authorizeRequests()
    <%_ if (authenticationType !== 'oauth2') { _%>
            .antMatchers("/api/authenticate").permitAll()
    <%_ } _%>
    <%_ if (authenticationType !== 'oauth2' && !skipUserManagement) { _%>
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/activate").permitAll()
            .antMatchers("/api/account/reset-password/init").permitAll()
            .antMatchers("/api/account/reset-password/finish").permitAll()
    <%_ } _%>
    <%_ if (authenticationType === 'oauth2') { _%>
            .antMatchers("/api/auth-info").permitAll()
    <%_ } _%>
            .antMatchers("/api/**").authenticated()
    <%_ if (websocket === 'spring-websocket') { _%>
            .antMatchers("/websocket/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
            .antMatchers("/websocket/**").permitAll()
    <%_ } _%>
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/info").permitAll()
            .antMatchers("/management/prometheus").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)<%_ if (authenticationType === 'session') { %>;<% } %>
    <%_ if (authenticationType === 'jwt') { _%>
        <%_ if (applicationType === 'monolith') { _%>
        .and()
            .httpBasic()
        <%_ } _%>
        .and()
            .apply(securityConfigurerAdapter());
    <%_ } else if (authenticationType === 'oauth2') { _%>
        <%_ if (['monolith', 'gateway'].includes(applicationType)) { _%>
        .and()
            .oauth2Login()
        <%_ } _%>
        .and()
            .oauth2ResourceServer()
                .jwt()
                .jwtAuthenticationConverter(authenticationConverter())
                .and()
            .and()
                .oauth2Client();
    <%_ } _%>
        // @formatter:on
    }
    <%_ if (authenticationType === 'jwt') { _%>

    private JWTConfigurer securityConfigurerAdapter() {
        return new JWTConfigurer(tokenProvider);
    }
    <%_ } _%>
    <%_ if (authenticationType === 'oauth2') { _%>

    Converter<Jwt, AbstractAuthenticationToken> authenticationConverter() {
        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(new JwtGrantedAuthorityConverter());
        return jwtAuthenticationConverter;
    }
        <%_ if (applicationType !== 'microservice') { _%>
    /**
     * Map authorities from "groups" or "roles" claim in ID Token.
     *
     * @return a {@link GrantedAuthoritiesMapper} that maps groups from
     * the IdP to Spring Security Authorities.
     */
    @Bean
    public GrantedAuthoritiesMapper userAuthoritiesMapper() {
        return (authorities) -> {
            Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

            authorities.forEach(authority -> {
                // Check for OidcUserAuthority because Spring Security 5.2 returns
                // each scope as a GrantedAuthority, which we don't care about.
                if (authority instanceof OidcUserAuthority) {
                    OidcUserAuthority oidcUserAuthority = (OidcUserAuthority) authority;
                    mappedAuthorities.addAll(SecurityUtils.extractAuthorityFromClaims(oidcUserAuthority.getUserInfo().getClaims()));
                }
            });
            return mappedAuthorities;
        };
    }
        <%_ } _%>

    @Bean
    JwtDecoder jwtDecoder() {
        NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromOidcIssuerLocation(issuerUri);

        OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(jHipsterProperties.getSecurity().getOauth2().getAudience());
        OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
        OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

        jwtDecoder.setJwtValidator(withAudience);

        return jwtDecoder;
    }
        <%_ if (applicationType === 'gateway' && serviceDiscoveryType) { _%>

    @Bean
    public AuthorizationHeaderFilter authHeaderFilter(AuthorizationHeaderUtil headerUtil) {
        return new AuthorizationHeaderFilter(headerUtil);
    }
        <%_ } _%>
    <%_ } _%>
}
<%_ } _%>
<%_ if (authenticationType === 'uaa') { _%>
import <%= packageName %>.config.oauth2.OAuth2JwtAccessTokenConverter;
import <%= packageName %>.config.oauth2.OAuth2Properties;
import <%= packageName %>.security.oauth2.OAuth2SignatureVerifierClient;
import <%= packageName %>.security.AuthoritiesConstants;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
    <%_ if (applicationType === 'gateway') { _%>
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CorsFilter;
    <%_ } _%>
import org.springframework.web.client.RestTemplate;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends ResourceServerConfigurerAdapter {
    private final OAuth2Properties oAuth2Properties;

    <%_ if (applicationType === 'gateway') { _%>
    private final CorsFilter corsFilter;

    <%_ } _%>
    public SecurityConfiguration(OAuth2Properties oAuth2Properties<% if (applicationType === 'gateway') { %>, CorsFilter corsFilter<% } %>) {
        this.oAuth2Properties = oAuth2Properties;
    <%_ if (applicationType === 'gateway') { _%>
        this.corsFilter = corsFilter;
    <%_ } _%>
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
    <%_ if (applicationType === 'gateway') { _%>
            .ignoringAntMatchers("/h2-console/**")
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
            .addFilterBefore(corsFilter, CsrfFilter.class)
    <%_ } else { _%>
            .disable()
    <%_ } _%>
            .headers()
            .frameOptions()
            .disable()
        .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/info").permitAll()
            .antMatchers("/management/prometheus").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
    }

    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
        return new JwtTokenStore(jwtAccessTokenConverter);
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(OAuth2SignatureVerifierClient signatureVerifierClient) {
        return new OAuth2JwtAccessTokenConverter(oAuth2Properties, signatureVerifierClient);
    }

    @Bean
    @Qualifier("loadBalancedRestTemplate")
    public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) {
        RestTemplate restTemplate = new RestTemplate();
        customizer.customize(restTemplate);
        return restTemplate;
    }
}
<%_ } _%>
